import {validatenull} from './validate'
//表单序列化
export const serialize = data => {
  let list = [];
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&');
};
export const getObjType = obj => {
  let toString = Object.prototype.toString;
  let map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return map[toString.call(obj)];
};
export const getViewDom = () => {
  return window.document.getElementById('avue-view').getElementsByClassName('el-scrollbar__wrap')[0]
}
/**
 * 对象深拷贝
 */
export const deepClone = data => {
  if (data == null) {
    return data;
  }
  let type = getObjType(data);
  let obj;
  if (type === 'array') {
    obj = [];
  } else if (type === 'object') {
    obj = {};
  } else {
    //不再具有下一层次
    return data;
  }
  if (type === 'array') {
    for (let i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]));
    }
  } else if (type === 'object') {
    for (let key in data) {
      obj[key] = deepClone(data[key]);
    }
  }
  return obj;
};
/**
 * 设置灰度模式
 */
export const toggleGrayMode = (status) => {
  if (status) {
    document.body.className = document.body.className + ' grayMode';
  } else {
    document.body.className = document.body.className.replace(' grayMode', '');
  }
};
/**
 * 设置主题
 */
export const setTheme = (name) => {
  document.body.className = name;
}

/**
 * 加密处理
 */
export const encryption = (params) => {
  let {
    data,
    type,
    param,
    key
  } = params;
  let result = JSON.parse(JSON.stringify(data));
  if (type == 'Base64') {
    param.forEach(ele => {
      result[ele] = btoa(result[ele]);
    })
  } else if (type == 'Aes') {
    param.forEach(ele => {
      result[ele] = window.CryptoJS.AES.encrypt(result[ele], key).toString();
    })

  }
  return result;
};


/**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
  if (fullscreenEnable()) {
    exitFullScreen();
  } else {
    reqFullScreen();
  }
};
/**
 * esc监听全屏
 */
export const listenfullscreen = (callback) => {
  function listen() {
    callback()
  }

  document.addEventListener("fullscreenchange", function () {
    listen();
  });
  document.addEventListener("mozfullscreenchange", function () {
    listen();
  });
  document.addEventListener("webkitfullscreenchange", function () {
    listen();
  });
  document.addEventListener("msfullscreenchange", function () {
    listen();
  });
};
/**
 * 浏览器判断是否全屏
 */
export const fullscreenEnable = () => {
  let isFullscreen = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
  return isFullscreen;
}

/**
 * 浏览器全屏
 */
export const reqFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.documentElement.requestFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.documentElement.webkitRequestFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen();
  }
};
/**
 * 浏览器退出全屏
 */
export const exitFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.exitFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.webkitCancelFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.mozCancelFullScreen();
  }
};
/**
 * 递归寻找子类的父类
 */

export const findParent = (menu, id) => {
  for (let i = 0; i < menu.length; i++) {
    if (menu[i].children.length != 0) {
      for (let j = 0; j < menu[i].children.length; j++) {
        if (menu[i].children[j].id == id) {
          return menu[i];
        } else {
          if (menu[i].children[j].children.length != 0) {
            return findParent(menu[i].children[j].children, id);
          }
        }
      }
    }
  }
};
/**
 * 判断2个对象属性和值是否相等
 */

/**
 * 动态插入css
 */

export const loadStyle = url => {
  const link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.href = url;
  const head = document.getElementsByTagName('head')[0];
  head.appendChild(link);
};
/**
 * 判断路由是否相等
 */
export const diff = (obj1, obj2) => {
  delete obj1.close;
  let o1 = obj1 instanceof Object;
  let o2 = obj2 instanceof Object;
  if (!o1 || !o2) { /*  判断不是对象  */
    return obj1 === obj2;
  }

  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
    //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
  }

  for (let attr in obj1) {
    let t1 = obj1[attr] instanceof Object;
    let t2 = obj2[attr] instanceof Object;
    if (t1 && t2) {
      return diff(obj1[attr], obj2[attr]);
    } else if (obj1[attr] !== obj2[attr]) {
      return false;
    }
  }
  return true;
}
/**
 * 根据字典的value显示label
 */
export const findByProp = (dic, key, keyProp = 'value', valueProp = 'label') => {
  if (validatenull(dic)) {
    if (key == null) {
      return '';
    } else if (key instanceof Array) {
      return key.join(',');
    } else {
      return key;
    }
  }
  if (key == null || typeof (key) == 'string' || typeof (key) == 'number' || typeof (key) == 'boolean' || key instanceof String || key instanceof Number) {
    let index = 0;
    index = findArray(dic, key, keyProp);
    if (index != -1) {
      return dic[index][valueProp];
    } else {
      return key;
    }
  } else if (key instanceof Array) {
    if (key.length == 0) {
      return '';
    }
    let resultList = [];
    let index = 0;
    key.forEach(ele => {
      index = findArray(dic, ele, keyProp);
      if (index != -1) {
        resultList.push(dic[index][valueProp]);
      } else {
        resultList.push(ele);
      }
    });
    return resultList.join(',');
  } else {
    return key;
  }
};
/**
 * 根据字典的value查找对应的index
 */
export const findArray = (dic, key, keyProp = 'value') => {
  for (let i = 0; i < dic.length; i++) {
    if (dic[i][keyProp] == key) {
      return i;
    }
  }
  return -1;
};
export const findObjectList = (dic, value, propName = 'value') => {
  let objectList = [];
  for (let i = 0; i < dic.length; i++) {
    if (dic[i][propName] == value) {
      objectList.push(dic[i]);
    }
  }
  return objectList;
};
/**
 * 根据字典的value查找对应的index
 */
export const findObject = (dic, key, keyProp = 'value') => {
  for (let i = 0; i < dic.length; i++) {
    if (dic[i][keyProp] == key) {
      return dic[i];
    }
  }
  return null;
};

export const transformObject = (obj, propList) => {
  let newObj = {};
  propList.forEach(prop => {
    newObj[prop.to] = obj[prop.from];
  });
  return newObj;
};
export const transformObjectList = (list, propList) => {
  if (list == null || list.length == 0 || propList == null || propList.length == 0) {
    return list;
  }
  let result = [];
  list.forEach(item => {
    result.push(transformObject(item, propList));
  });
  return result;
};

export const refineValue = (obj, from, to) => {
  return refineObject(obj, [{from: from, to: to}]);
};

export const refineObject = (obj, convert = [], fromName = 'from', toName = 'to') => {
  if (obj == null || convert == null || convert.length == 0) {
    return obj;
  }
  if ((typeof obj) == 'string' || (typeof obj) == 'number' || typeof (obj) == 'boolean' || obj instanceof String || obj instanceof Number) {
    for (let i = 0; i < convert.length; i++) {
      if (convert[i][fromName] != null && convert[i][fromName] instanceof Array) {
        let fromList = convert[i][fromName];
        for (let n = 0; n < fromList.length; n++) {
          if (fromList[n] == obj) {
            return convert[i][toName];
          }
        }
      } else if (obj == convert[i][fromName]) {
        return convert[i][toName];
      }
    }
    return obj;
  }
  if (obj instanceof Function) {
    return obj;
  }
  if (obj instanceof Array) {
    for (let i = 0; i < obj.length; i++) {
      obj[i] = refineObject(obj[i], convert);
    }
    return obj;
  }
  let keys = Object.keys(obj);
  keys.forEach(key => {
    obj[key] = refineObject(obj[key], convert);
  });
  return obj;
};
/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = '';
  random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len ? len : 4);
  if (date) random = random + Date.now();
  return random;
};
/**
 * 打开小窗口
 */
export const openWindow = (url, title, w, h) => {
  // Fixes dual-screen position                            Most browsers       Firefox
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top

  const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
  const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height

  const left = ((width / 2) - (w / 2)) + dualScreenLeft
  const top = ((height / 2) - (h / 2)) + dualScreenTop
  const newWindow = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus()
  }
}

/**
 * 获取顶部地址栏地址
 */
export const getTopUrl = () => {
  return window.location.origin
  // return window.location.href.split("/#/")[0];
}

/**
 * 获取url参数
 * @param name 参数名
 */
export const getQueryString = (name) => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  let r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(decodeURI(r[2]));
  return null;
}

export const generateColumnStyle = (style) => {
  if (style == null || style == '') {
    return '';
  } else {
    return 'style="' + style + '"';
  }
}
export const generateTable = (title, headers, rowList, bottom) => {
  let columnCount = 1;
  if (headers != null && headers.length > 0) {
    columnCount = headers.length;
  } else if (rowList != null && rowList.length > 0) {
    columnCount = rowList[0].length;
  }
  let resultList = [];
  resultList.push('<table border="1">');
  if (title != null && title.data != null && title.data != '') {
    resultList.push('<tr>');
    resultList.push('<td ' + generateColumnStyle(title.style) + ' colspan="' + columnCount + '">' + title.data + '</td>');
    resultList.push('</tr>');
  }
  if (headers != null && headers.length > 0) {
    resultList.push('<tr>');
    headers.forEach((header) => {
      resultList.push('<td ' + generateColumnStyle(header.style) + '>' + header.data + '</td>');
    });
    resultList.push('</tr>');
  }
  if (rowList != null && rowList.length > 0) {
    rowList.forEach((row) => {
      resultList.push('<tr>');
      if (row == null || row.length == 0) {
        resultList.push('<td colspan="' + columnCount + '"></td>');
      } else if (row.length == 1) {
        resultList.push('<td ' + generateColumnStyle(row[0].style) + ' colspan="' + columnCount + '">' + row[0].data + '</td>');
      } else {
        row.forEach((item) => {
          resultList.push('<td ' + generateColumnStyle(item.style) + ((item.colspan == null || item.colspan < 1) ? '' : ' colspan="' + item.colspan + '"') + '>' + item.data + '</td>');
        });
      }
      resultList.push('</tr>');
    });
  }
  if (bottom != null && bottom.length == 2) {
    resultList.push('<tr>');
    resultList.push('<td>' + bottom[0].data + '</td>');
    resultList.push('<td colspan="' + (columnCount - 1) + '">' + bottom[1].data + '</td>');
    resultList.push('</tr>');
  }
  resultList.push('</table>');
  return resultList.join("");
}

export const exportExcel = (contentTagName, title, headers, rowList, bottom, filename) => {
  // 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
  let html = "<html><head><meta charset='utf-8' /></head><body>" + generateTable(title, headers, rowList, bottom) + "</body></html>";
  // 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
  let blob = new Blob([html], {type: "application/vnd.ms-excel"});

  let content = document.getElementById(contentTagName);
  let linkEle = document.createElement("a");
  content.appendChild(linkEle);

  // 利用URL.createObjectURL()方法为a元素生成blob URL
  linkEle.target = '_blank';
  linkEle.href = URL.createObjectURL(blob);
  // 设置文件名
  linkEle.download = filename;
  linkEle.click();
  linkEle.remove();
}

export const exportExcel2 = (title, headers, rowList, bottom, filename) => {
  // 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
  let html =
    "<html xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40' lang='zh-CN'>" +
    "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>" + filename + "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->" +
    "<meta name=ProgId content=Excel.Sheet>" +
    "<meta charset='utf-8' />" +
    "<meta name=Generator content='Microsoft Excel 15'><title></title></head>" +
    "<body>" + generateTable(title, headers, rowList, bottom) + "</body></html>";
  // 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
  let blob = new Blob([html], {type: "application/vnd.ms-excel"});
  let linkEle = document.createElement("a");
  linkEle.target = '_blank';
  linkEle.href = URL.createObjectURL(blob);
  // 设置文件名
  linkEle.download = filename + ".xls";
  linkEle.click();
  linkEle.remove();
}

/**
 * 根据字典的value显示label
 */
export const findByvalue = (dic, value) => {
  let result = '';
  if (validatenull(dic)) return value;
  if (typeof (value) == 'string' || typeof (value) == 'number' || typeof (value) == 'boolean') {
    let index = 0;
    index = findArray(dic, value);
    if (index != -1) {
      result = dic[index].label;
    } else {
      result = value;
    }
  } else if (value instanceof Array && dic[0].children) {
    let index = 0;
    let count = 0
    while (count < value.length) {
      index = findArray(dic, value[count]);
      if (!validatenull(dic[index])) {
        result = result + dic[index].label + '/';
        dic = dic[index].children;
      }
      count++;
    }
    result = result.substr(0, result.length - 1);

  } else if (value instanceof Array) {
    result = [];
    let index = 0;
    value.forEach(ele => {
      index = findArray(dic, ele);
      if (index != -1) {
        result.push(dic[index].label);
      } else {
        result.push(value);
      }
    });
    result = result.toString();
  }
  return result;
}

/**
 * 获取字典
 */
export const setDic = (dicData, DIC) => {
  return (typeof (dicData) == 'string') ? DIC : dicData
}

/**
 * 设置px
 */
export const setPx = (val, defval) => {
  if (validatenull(val)) {
    val = defval;
  }
  val = val + '';
  if (val.indexOf('%') == -1) {
    val = val + 'px';
  }
  return val;
}

/**
 * 千分符格式化
 * @param num
 * @returns {string}
 */
export const thousandSeparator = (num) => {
  let source = String(num).split(".");//按小数点分成2部分
  source[0] = source[0].replace(new RegExp('(\\d)(?=(\\d{3})+$)','ig'),"$1,");//只将整数部分进行都好分割
  return source.join(".");//再将小数部分合并进来
}

/**
 * 生成列标注
 * @param h
 * @param column
 * @param content
 * @returns {*}
 */
export const columnTip = (h, column, content) => {
  return h('span', [
    h('el-tooltip', {
      props: {
        effect: 'dark',
        placement: 'top',
      },
    }, [
      h('i', {
        class: 'el-icon-question',
        style: 'color:#409EFF; margin-right:5px;'
      }),
      h('div', {
        slot: 'content',
        // 为支持文字可以用html
        domProps:{
          innerHTML: content
        }
      })
    ]),
    h('span', column.label)
  ])
}

